<?php

/**
 * Modelo de datos personales, requiere sesion ACL iniciada
 *
 * @category Zwei
 * @package Models
 * @version $Id:$
 * @since 0.1
 *
 */

class PersonalInfoModel extends Zwei_Db_Table
{
	protected $_name = "acl_users";
	protected $_name_roles = "acl_roles";
	protected $_name_persona = "persona";
	protected $_generate_pass = "user_name";
	protected $_user_name;

	public function init()
	{
		if(!Zend_Auth::getInstance()->hasIdentity()) $this->_redirect('index/login');
		$userInfo = Zend_Auth::getInstance()->getStorage()->read();
		$this->_user_name = $userInfo->user_name;
	}

	public function select()
	{
		$this->setAdapter("dn");
		$oSelect=new Zend_Db_Table_Select($this);
		$oSelect->setIntegrityCheck(false); //de lo contrario no podemos hacer JOIN
		$oSelect->from($this->_name, array("id", "user_name", "acl_roles_id"))
		->joinLeft($this->_name_persona, "$this->_name.id = $this->_name_persona.USER_ID", array("NOMBRES", "APELLIDO_P", "APELLIDO_M", "EMAIL"))
		->joinLeft($this->_name_roles, "$this->_name.acl_roles_id = $this->_name_roles.id", "role_name")
		;
		$oSelect->where($this->getAdapter()->quoteInto('user_name = ?', $this->_user_name));
		return $oSelect;
	}

	/**
     * No se puede insertar un usuario "yo mismo"
	 */
    public function insert() 
    {
    	$this->setMessage("Get Lost Muppet");
    	return false;
    }
	
	/**
	 * Captura de excepciones posibles como nombre de usuario en uso
	 */

	public function update($data, $where)
	{
		$this->setAdapter("dn");
		$personadata = array();
        if (isset($data["NOMBRES"])) {
        	$personadata["NOMBRES"] = $data["NOMBRES"];
        	unset($data["NOMBRES"]);
        }
        
        if (isset($data["APELLIDO_P"])) {
            $personadata["APELLIDO_P"] = $data["APELLIDO_P"];
            unset($data["APELLIDO_P"]);	
        }
        
        if (isset($data["APELLIDO_M"])) {
            $personadata["APELLIDO_M"] = $data["APELLIDO_M"];
            unset($data["APELLIDO_M"]);         	
        }

        if (isset($data["NOMBRES"])) {
        	$personadata["NOMBRES"] = $data["NOMBRES"];
            unset($data["NOMBRES"]);
        }    
        
        if (isset($data["EMAIL"])) {
        	$personadata["EMAIL"] = $data["EMAIL"];
            unset($data["EMAIL"]);
        } 
        
        
        $oSelect = new Zend_Db_Table_Select($this); 
        $oSelect
            ->from($this->_name, array('id'))
            ->where($this->getAdapter()->quoteInto("user_name = ?", $this->_user_name));

        $rs = $this->fetchAll($oSelect);

        $personadata['USER_ID'] = $rs[0]["id"];
        
        $update = false;
        if (count($data) > 0) {
			try {
				$update = parent::update($data, $where);
    			if (is_object($this->getAdapter()->getProfiler()->getLastQueryProfile())) {
                    $query = $this->getAdapter()->getProfiler()->getLastQueryProfile()->getQuery();
                    $query_params = print_r($this->getAdapter()->getProfiler()->getLastQueryProfile()->getQueryParams(),true);
                    $this->getAdapter()->getProfiler()->setEnabled(false);
                    Zwei_Utils_Debug::write("[TRANSACTION:{$this->_form->action}]\nUser:{$this->_user_info->user_name}\nQuery:$query\nQuery Params:$query_params",  "../log/transactions");
                } else {
                    $log_data = print_r($data, true);
                    $log_where = print_r($where, true);
                    Zwei_Utils_Debug::write("Se modificó {$this->_name} TRANSACTION:{$this->_form->action} \nUser:{$this->_user_info->user_name} \nData:$log_data \nWhere:$log_where", "../log/transactions");
                }
			
			} catch(Zend_Db_Exception $e) {
				if($e->getCode() == '23000'){
					$this->setMessage('Nombre de Usuario en uso.');
					return false;
				}else{
					Zwei_Utils_Debug::write("error:".$e->getMessage()."code".$e->getCode());
				}
			}
        }
		
        if (count($personadata) > 0) {
	        $persona = new PersonaModel();
	        $where = $this->getAdapter()->quoteInto("USER_ID = ? ", $personadata['USER_ID']);
	        $insert = false;
	        //En casos legacy pueden haber usuarios sin persona asociada :(
	        try {
	        	$insert = $persona->insert($personadata);
	        } catch (Zend_Db_Exception $e) {
	        	Zwei_Utils_Debug::write("error:".$e->getMessage()."code".$e->getCode());
	            $update2 = $persona->update($personadata, $where);	
	        }
	
            if (is_object($this->getAdapter()->getProfiler()->getLastQueryProfile())) {
                $query = $this->getAdapter()->getProfiler()->getLastQueryProfile()->getQuery();
                $query_params = print_r($this->getAdapter()->getProfiler()->getLastQueryProfile()->getQueryParams(),true);
                $this->getAdapter()->getProfiler()->setEnabled(false);
                Zwei_Utils_Debug::write("[TRANSACTION:Se modificó {$this->_name}] update \nUser:{$this->_user_info->user_name}\nQuery:$query\nQuery Params:$query_params",  "../log/transactions");
            } else if ($insert || $update2) {
                $log_data = print_r($personadata, true);
                $log_where = print_r($where, true);
                Zwei_Utils_Debug::write("TRANSACTION: Se modificó {$this->_name} TRANSACTION:update \nData:$log_data \nWhere:$log_where", "../log/transactions");
            }
	        
	        if (!$update && isset($insert)) $update = $insert;
			if (!$update) $update = $update2;
        }
		return $update;

	}
}
